/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package hu.bme.j2ee.v37zen.web.beans;

import hu.bme.j2ee.v37zen.beans.FindUsersBean;
import hu.bme.j2ee.v37zen.beans.LoginBean;
import hu.bme.j2ee.v37zen.entities.User;
import java.io.Serializable;
import java.security.Principal;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;

/**
 *
 * @author Kiss Dániel
 */
@ManagedBean(name="userManager")
@RequestScoped
public class UserManager implements Serializable {
    private static final long serialVersionUID = -8414917273021332315L;
    
    private User user; // The JPA entity.

    @EJB
    private FindUsersBean fub;
    @EJB
    private LoginBean lb;

    public User getUser() {
        Principal principal = FacesContext.getCurrentInstance().getExternalContext().getUserPrincipal();
        if (principal != null) {
            user = fub.findUserByUsername(principal.getName());
            if(user == null){
                FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
                return null;
            }
            user = lb.loginUser(user);
        }
        return user;
    }
      
    public String logout(){
        
        User user_ = this.getUser();
        lb.loginOut(user_);
        this.user = null;        
        FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
        
        //System.out.println("[SD-war] logout | " + user.toString());
        
        return "index.xhtml?faces-redirect=true";
    }
}
